package com.shinhye.elephantsafe;

import com.shinhye.elephantsafe.utils.MD5Utils;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class WatchDogInterceptActivity extends Activity {

	private TextView tv_appname;
	private ImageView iv_appicon;
	private EditText et_psw;
	private String packname;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_watchdog_intercept);
		
		tv_appname = (TextView) findViewById(R.id.tv_appname);
		iv_appicon = (ImageView) findViewById(R.id.iv_appicon);
		et_psw = (EditText) findViewById(R.id.et_psw);
		
		Intent intent = getIntent();
		packname = intent.getStringExtra("packname");
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packInfo = pm.getPackageInfo(packname, 0);
			Drawable icon = packInfo.applicationInfo.loadIcon(pm);
			String name = packInfo.applicationInfo.loadLabel(pm).toString();
			
			tv_appname.setText(name);
			iv_appicon.setImageDrawable(icon);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory("android.intent.category.HOME");
		startActivity(intent);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		finish();
	}
	
	public void enterapplock(View v) {
		SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
		String espsw = sp.getString("password", "");
		
		String psw = et_psw.getText().toString().trim();
		if(TextUtils.isEmpty(psw)) {
			Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
		} else if(!espsw.equals(MD5Utils.md5(psw))) {
			Toast.makeText(this, "密码不正确！", Toast.LENGTH_SHORT).show();
		} else {
			finish();
			
			Intent intent = new Intent("com.shinhye.elephantsafe.stoplockapp");
			intent.putExtra("packagename", packname);
			sendBroadcast(intent);
		}
	}
}
